package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.IYddHomeService;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/home/index")
@Slf4j
@CrossOrigin
public class YddHomeController {
    @Autowired
    private IYddHomeService yddHomeService;

    @PostMapping("/login")
    public ResultData login(@RequestBody YddUser yddUser) {
        log.info("登陆用户：{}", yddUser.toString());

        String mobile = yddUser.getMobile();
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUser::getMobile, mobile);
        YddUser one = yddHomeService.getOne(wrapper);
        if (one == null) {
            return ResultData.error("账号不存在");
        }

        String password = yddUser.getPassword();
        if (one.getPassword().equals(generatePassword(password))) {
            //把用户id 加密进token里

            // 生成token信息
            Map tokenMap = new HashMap<>();
            tokenMap.put("userId", one.getId().toString());
            tokenMap.put("username",one.getUsername());
            String token = JwtUtils.getToken(tokenMap);

            Map data = new HashMap();
            data.put("token",token);
            return ResultData.ok("登陆成功",data);
        }
        return ResultData.error("密码错误");
    }

    /**
     * md5加密
     *
     * @param password 密码
     */
    private String generatePassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }
}
